<!DOCTYPE html>





<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="generator" content="Hexo 3.9.0">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.3.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.3.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.3.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '7.3.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    save_scroll: false,
    copycode: {"enable":false,"show_result":false,"style":null},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    }
  };
</script>

  <meta name="description" content="Server的生命周期1. 创建1int socket(int domain, int type, int protocol);  2. 绑定1int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);  3. 监听1int listen(int sockfd, int backlog);  4. 接收1int acce">
<meta name="keywords" content="socket编程">
<meta property="og:type" content="article">
<meta property="og:title" content="socket编程">
<meta property="og:url" content="http://yoursite.com/2019/06/24/socket编程/index.html">
<meta property="og:site_name" content="XuQi&#39;s Blog">
<meta property="og:description" content="Server的生命周期1. 创建1int socket(int domain, int type, int protocol);  2. 绑定1int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);  3. 监听1int listen(int sockfd, int backlog);  4. 接收1int acce">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://yoursite.com/2019/06/24/socket编程/305504-20150918012828961-1176245587.png">
<meta property="og:updated_time" content="2019-10-20T13:23:23.045Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="socket编程">
<meta name="twitter:description" content="Server的生命周期1. 创建1int socket(int domain, int type, int protocol);  2. 绑定1int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);  3. 监听1int listen(int sockfd, int backlog);  4. 接收1int acce">
<meta name="twitter:image" content="http://yoursite.com/2019/06/24/socket编程/305504-20150918012828961-1176245587.png">
  <link rel="canonical" href="http://yoursite.com/2019/06/24/socket编程/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>socket编程 | XuQi's Blog</title>
  








  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  <div class="container sidebar-position-left">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">XuQi's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
  </ul>

    

</nav>
</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content page-post-detail">
            

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/06/24/socket编程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="XuQi">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="XuQi's Blog">
    </span>
      <header class="post-header">

        
          <h1 class="post-title" itemprop="name headline">socket编程

            
          </h1>
        

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2019-06-24 08:18:31" itemprop="dateCreated datePublished" datetime="2019-06-24T08:18:31+00:00">2019-06-24</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-10-20 13:23:23" itemprop="dateModified" datetime="2019-10-20T13:23:23+00:00">2019-10-20</time>
              </span>
            
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="Server的生命周期"><a href="#Server的生命周期" class="headerlink" title="Server的生命周期"></a>Server的生命周期</h3><h4 id="1-创建"><a href="#1-创建" class="headerlink" title="1. 创建"></a>1. 创建</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">socket</span><span class="params">(<span class="keyword">int</span> domain, <span class="keyword">int</span> type, <span class="keyword">int</span> protocol)</span></span>;</span><br></pre></td></tr></table></figure>

<h4 id="2-绑定"><a href="#2-绑定" class="headerlink" title="2. 绑定"></a>2. 绑定</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">bind</span><span class="params">(<span class="keyword">int</span> sockfd, <span class="keyword">const</span> struct sockaddr *addr,<span class="keyword">socklen_t</span> addrlen)</span></span>;</span><br></pre></td></tr></table></figure>

<h4 id="3-监听"><a href="#3-监听" class="headerlink" title="3. 监听"></a>3. 监听</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">listen</span><span class="params">(<span class="keyword">int</span> sockfd, <span class="keyword">int</span> backlog)</span></span>;</span><br></pre></td></tr></table></figure>

<h4 id="4-接收"><a href="#4-接收" class="headerlink" title="4. 接收"></a>4. 接收</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">accept</span><span class="params">(<span class="keyword">int</span> sockfd, struct sockaddr *addr, <span class="keyword">socklen_t</span> *addrlen)</span></span>;</span><br></pre></td></tr></table></figure>

<h4 id="5-结束"><a href="#5-结束" class="headerlink" title="5. 结束"></a>5. 结束</h4><a id="more"></a>

<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/socket.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/un.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> MY_SOCK_PATH <span class="meta-string">"/somepath"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> LISTEN_BACKLOG 50</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> handle_error(msg) \</span></span><br><span class="line">           <span class="keyword">do</span> &#123; perror(msg); <span class="built_in">exit</span>(EXIT_FAILURE); &#125; <span class="keyword">while</span> (<span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> sfd, cfd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">sockaddr_un</span> <span class="title">my_addr</span>, <span class="title">peer_addr</span>;</span></span><br><span class="line">    <span class="keyword">socklen_t</span> peer_addr_size;</span><br><span class="line"></span><br><span class="line">    sfd = socket(AF_UNIX, SOCK_STREAM, <span class="number">0</span>);</span><br><span class="line">    <span class="keyword">if</span> (sfd == <span class="number">-1</span>)</span><br><span class="line">        handle_error(<span class="string">"socket"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="built_in">memset</span>(&amp;my_addr, <span class="number">0</span>, <span class="keyword">sizeof</span>(struct sockaddr_un));</span><br><span class="line">    <span class="comment">/* Clear structure */</span></span><br><span class="line">    my_addr.sun_family = AF_UNIX;</span><br><span class="line">    <span class="built_in">strncpy</span>(my_addr.sun_path, MY_SOCK_PATH,</span><br><span class="line">            <span class="keyword">sizeof</span>(my_addr.sun_path) - <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (bind(sfd, (struct sockaddr *) &amp;my_addr,</span><br><span class="line">             <span class="keyword">sizeof</span>(struct sockaddr_un)) == <span class="number">-1</span>)</span><br><span class="line">        handle_error(<span class="string">"bind"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (listen(sfd, LISTEN_BACKLOG) == <span class="number">-1</span>)</span><br><span class="line">        handle_error(<span class="string">"listen"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* Now we can accept incoming connections one</span></span><br><span class="line"><span class="comment">              at a time using accept(2) */</span></span><br><span class="line"></span><br><span class="line">    peer_addr_size = <span class="keyword">sizeof</span>(struct sockaddr_un);</span><br><span class="line">    cfd = accept(sfd, (struct sockaddr *) &amp;peer_addr,</span><br><span class="line">                 &amp;peer_addr_size);</span><br><span class="line">    <span class="keyword">if</span> (cfd == <span class="number">-1</span>)</span><br><span class="line">        handle_error(<span class="string">"accept"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* Code to deal with incoming connection(s)... */</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">/* When no longer required, the socket pathname, MY_SOCK_PATH</span></span><br><span class="line"><span class="comment">              should be deleted using unlink(2) or remove(3) */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Client的生命周期"><a href="#Client的生命周期" class="headerlink" title="Client的生命周期"></a>Client的生命周期</h3><h4 id="1-创建-1"><a href="#1-创建-1" class="headerlink" title="1. 创建"></a>1. 创建</h4><h4 id="2-绑定-一般不会使用"><a href="#2-绑定-一般不会使用" class="headerlink" title="2. 绑定 (一般不会使用)"></a>2. 绑定 (一般不会使用)</h4><h4 id="3-连接"><a href="#3-连接" class="headerlink" title="3. 连接"></a>3. 连接</h4><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">connect</span><span class="params">(<span class="keyword">int</span> sockfd, <span class="keyword">const</span> struct sockaddr *addr,<span class="keyword">socklen_t</span> addrlen)</span></span>;</span><br></pre></td></tr></table></figure>

<h4 id="4-结束"><a href="#4-结束" class="headerlink" title="4. 结束"></a>4. 结束</h4><h3 id="套接字读操作"><a href="#套接字读操作" class="headerlink" title="套接字读操作"></a>套接字读操作</h3><h4 id="读取长度"><a href="#读取长度" class="headerlink" title="读取长度"></a>读取长度</h4><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ssize_t</span> read(<span class="keyword">int</span> fd, <span class="keyword">void</span> *buf, <span class="keyword">size_t</span> count);</span><br></pre></td></tr></table></figure>

<p>一直读取发送给服务器，如果不限制长度，会导致服务器block在read</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tail -f /var/log/system.log | nc localhost 4481</span><br></pre></td></tr></table></figure>

<h4 id="EOF事件"><a href="#EOF事件" class="headerlink" title="EOF事件"></a>EOF事件</h4><p>服务器读取固定长度，但是如果长度不够的话，只要有EOF，就会停止读取，客户端最简单的方式发EOF就是关闭套接字。</p>
<h4 id="部分读取"><a href="#部分读取" class="headerlink" title="部分读取"></a>部分读取</h4><p>只要有数据，就会读取，不等是否达到固定长度或者是否有EOF过来。</p>
<h3 id="套接字写操作"><a href="#套接字写操作" class="headerlink" title="套接字写操作"></a>套接字写操作</h3><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ssize_t</span> write(<span class="keyword">int</span> fd, <span class="keyword">const</span> <span class="keyword">void</span> *buf, <span class="keyword">size_t</span> count);</span><br></pre></td></tr></table></figure>

<h3 id="套接字选项字节"><a href="#套接字选项字节" class="headerlink" title="套接字选项字节"></a>套接字选项字节</h3><p><strong>TIME_WAIT状态</strong></p>
<blockquote>
<p>当你关闭（close）了某个缓冲区，但其中仍有未处理数据的套接字之时就会出现TIME_WAIT状态。前面曾说过，调用write只是保证数据已经进入了缓冲层。当你关闭一个套接字时，它未处理的数据并不会被丢弃。</p>
<p>在幕后，内核使连接保持足够长的打开时间，以便将未处理的数据发送完毕。这就意味着它必须发送数据，然后等待接收方的确认，以免数据需要重传。<br>如果关闭一个尚有数据未处理的服务器并立刻将同一个地址绑定到另一个套接字上（比如重启服务器），则会引发一个<br>Errno::EADDRINUSE，除非未处理的数据被丢弃掉。设置<br>SO_REUSE_ADDR可以绕过这个问题，使你可以绑定到一个处于<br>TIME_WAIT状态的套接字所使用的地址上。</p>
</blockquote>
<h3 id="非阻塞式IO"><a href="#非阻塞式IO" class="headerlink" title="非阻塞式IO"></a>非阻塞式IO</h3><h3 id="连接复用"><a href="#连接复用" class="headerlink" title="连接复用"></a>连接复用</h3><p><a href="https://www.cnblogs.com/aspirant/p/9166944.html" target="_blank" rel="noopener">https://www.cnblogs.com/aspirant/p/9166944.html</a></p>
<p>IO多路复用是指内核一旦发现进程指定的一个或者多个IO条件准备读取，它就通知该进程。</p>
<h4 id="IO多路复用之select总结"><a href="#IO多路复用之select总结" class="headerlink" title="IO多路复用之select总结"></a>IO多路复用之select总结</h4><h5 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h5><p>该函数准许进程指示内核等待多个事件中的任何一个发送，并只在有一个或多个事件发生或经历一段指定的时间后才唤醒。函数原型如下</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/select.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">select</span><span class="params">(<span class="keyword">int</span> maxfdp1,fd_set *readset,fd_set *writeset,fd_set *exceptset,<span class="keyword">const</span> struct timeval *timeout)</span></span></span><br><span class="line">返回值：就绪描述符的数目，超时返回0，出错返回-1</span><br></pre></td></tr></table></figure>

<p>（1）第一个参数maxfdp1指定待测试的描述字个数，它的值是待测试的最大描述字加1（因此把该参数命名为maxfdp1），描述字0、1、2…maxfdp1-1均将被测试。</p>
<p>因为文件描述符是从0开始的。</p>
<p>（2）中间的三个参数readset、writeset和exceptset指定我们要让内核测试读、写和异常条件的描述字。如果对某一个的条件不感兴趣，就可以把它设为空指针。struct fd_set可以理解为一个集合，这个集合中存放的是文件描述符，可通过以下四个宏进行设置：</p>
<p>​          void FD_ZERO(fd_set *fdset);           //清空集合</p>
<p>​          void FD_SET(int fd, fd_set *fdset);   //将一个给定的文件描述符加入集合之中</p>
<p>​          void FD_CLR(int fd, fd_set *fdset);   //将一个给定的文件描述符从集合中删除</p>
<p>​          int FD_ISSET(int fd, fd_set *fdset);   // 检查集合中指定的文件描述符是否可以读写 </p>
<p>（3）timeout告知内核等待所指定描述字中的任何一个就绪可花多少时间。其timeval结构用于指定这段时间的秒数和微秒数。</p>
<p>​         struct timeval{</p>
<p>​                   long tv_sec;   //seconds</p>
<p>​                   long tv_usec;  //microseconds</p>
<p>​       };</p>
<p>这个参数有三种可能：</p>
<p>（1）永远等待下去：仅在有一个描述字准备好I/O时才返回。为此，把该参数设置为空指针NULL。</p>
<p>（2）等待一段固定时间：在有一个描述字准备好I/O时返回，但是不超过由该参数所指向的timeval结构中指定的秒数和微秒数。</p>
<p>（3）根本不等待：检查描述字后立即返回，这称为轮询。为此，该参数必须指向一个timeval结构，而且其中的定时器值必须为0。</p>
<h5 id="基本原理"><a href="#基本原理" class="headerlink" title="基本原理"></a>基本原理</h5><p><img src="/2019/06/24/socket编程/305504-20150918012828961-1176245587.png" alt="img"></p>
<h5 id="测试代码"><a href="#测试代码" class="headerlink" title="测试代码"></a>测试代码</h5><p>客户端向服务器发送信息，服务器接收并原样发送给客户端，客户端显示出接收到的信息。</p>
<p>服务端：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;errno.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;netinet/in.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/socket.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/select.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;netinet/in.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;arpa/inet.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;assert.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> IPADDR      <span class="meta-string">"127.0.0.1"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> PORT        8787</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> MAXLINE     1024</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> LISTENQ     5</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> SIZE        10</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">server_context_st</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="keyword">int</span> cli_cnt;        <span class="comment">/*客户端个数*/</span></span><br><span class="line">    <span class="keyword">int</span> clifds[SIZE];   <span class="comment">/*客户端的个数*/</span></span><br><span class="line">    fd_set allfds;      <span class="comment">/*句柄集合*/</span></span><br><span class="line">    <span class="keyword">int</span> maxfd;          <span class="comment">/*句柄最大值*/</span></span><br><span class="line">&#125; server_context_st;</span><br><span class="line"><span class="keyword">static</span> server_context_st *s_srv_ctx = <span class="literal">NULL</span>;</span><br><span class="line"><span class="comment">/*===========================================================================</span></span><br><span class="line"><span class="comment"> * ==========================================================================*/</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">create_server_proc</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span>* ip,<span class="keyword">int</span> port)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>  fd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">sockaddr_in</span> <span class="title">servaddr</span>;</span></span><br><span class="line">    fd = socket(AF_INET, SOCK_STREAM,<span class="number">0</span>);</span><br><span class="line">    <span class="keyword">if</span> (fd == <span class="number">-1</span>) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">"create socket fail,erron:%d,reason:%s\n"</span>,</span><br><span class="line">                errno, strerror(errno));</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/*一个端口释放后会等待两分钟之后才能再被使用，SO_REUSEADDR是让端口释放后立即就可以被再次使用。*/</span></span><br><span class="line">    <span class="keyword">int</span> reuse = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">if</span> (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &amp;reuse, <span class="keyword">sizeof</span>(reuse)) == <span class="number">-1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    bzero(&amp;servaddr,<span class="keyword">sizeof</span>(servaddr));</span><br><span class="line">    servaddr.sin_family = AF_INET;</span><br><span class="line">    inet_pton(AF_INET,ip,&amp;servaddr.sin_addr);</span><br><span class="line">    servaddr.sin_port = htons(port);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (bind(fd,(struct sockaddr*)&amp;servaddr,<span class="keyword">sizeof</span>(servaddr)) == <span class="number">-1</span>) &#123;</span><br><span class="line">        perror(<span class="string">"bind error: "</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    listen(fd,LISTENQ);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> fd;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">accept_client_proc</span><span class="params">(<span class="keyword">int</span> srvfd)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">sockaddr_in</span> <span class="title">cliaddr</span>;</span></span><br><span class="line">    <span class="keyword">socklen_t</span> cliaddrlen;</span><br><span class="line">    cliaddrlen = <span class="keyword">sizeof</span>(cliaddr);</span><br><span class="line">    <span class="keyword">int</span> clifd = <span class="number">-1</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"accpet clint proc is called.\n"</span>);</span><br><span class="line">    </span><br><span class="line">ACCEPT:</span><br><span class="line">    clifd = accept(srvfd,(struct sockaddr*)&amp;cliaddr,&amp;cliaddrlen);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (clifd == <span class="number">-1</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (errno == EINTR) &#123;</span><br><span class="line">            <span class="keyword">goto</span> ACCEPT;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">"accept fail,error:%s\n"</span>, strerror(errno));</span><br><span class="line">            <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">fprintf</span>(<span class="built_in">stdout</span>, <span class="string">"accept a new client: %s:%d\n"</span>,</span><br><span class="line">            inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//将新的连接描述符添加到数组中</span></span><br><span class="line">    <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; SIZE; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (s_srv_ctx-&gt;clifds[i] &lt; <span class="number">0</span>) &#123;</span><br><span class="line">            s_srv_ctx-&gt;clifds[i] = clifd;</span><br><span class="line">            s_srv_ctx-&gt;cli_cnt++;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (i == SIZE) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>,<span class="string">"too many clients.\n"</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="number">101</span> &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">handle_client_msg</span><span class="params">(<span class="keyword">int</span> fd, <span class="keyword">char</span> *buf)</span> </span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    assert(buf);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"recv buf is :%s\n"</span>, buf);</span><br><span class="line">    write(fd, buf, <span class="built_in">strlen</span>(buf) +<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">recv_client_msg</span><span class="params">(fd_set *readfds)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i = <span class="number">0</span>, n = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> clifd;</span><br><span class="line">    <span class="keyword">char</span> buf[MAXLINE] = &#123;<span class="number">0</span>&#125;;</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>;i &lt;= s_srv_ctx-&gt;cli_cnt;i++) &#123;</span><br><span class="line">        clifd = s_srv_ctx-&gt;clifds[i];</span><br><span class="line">        <span class="keyword">if</span> (clifd &lt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">/*判断客户端套接字是否有数据*/</span></span><br><span class="line">        <span class="keyword">if</span> (FD_ISSET(clifd, readfds)) &#123;</span><br><span class="line">            <span class="comment">//接收客户端发送的信息</span></span><br><span class="line">            n = read(clifd, buf, MAXLINE);</span><br><span class="line">            <span class="keyword">if</span> (n &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">/*n==0表示读取完成，客户都关闭套接字*/</span></span><br><span class="line">                FD_CLR(clifd, &amp;s_srv_ctx-&gt;allfds);</span><br><span class="line">                close(clifd);</span><br><span class="line">                s_srv_ctx-&gt;clifds[i] = <span class="number">-1</span>;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            handle_client_msg(clifd, buf);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle_client_proc</span><span class="params">(<span class="keyword">int</span> srvfd)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>  clifd = <span class="number">-1</span>;</span><br><span class="line">    <span class="keyword">int</span>  retval = <span class="number">0</span>;</span><br><span class="line">    fd_set *readfds = &amp;s_srv_ctx-&gt;allfds;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">timeval</span> <span class="title">tv</span>;</span></span><br><span class="line">    <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span> (<span class="number">1</span>) &#123;</span><br><span class="line">        <span class="comment">/*每次调用select前都要重新设置文件描述符和时间，因为事件发生后，文件描述符和时间都被内核修改啦*/</span></span><br><span class="line">        FD_ZERO(readfds);</span><br><span class="line">        <span class="comment">/*添加监听套接字*/</span></span><br><span class="line">        FD_SET(srvfd, readfds);</span><br><span class="line">        s_srv_ctx-&gt;maxfd = srvfd;</span><br><span class="line">        </span><br><span class="line">        tv.tv_sec = <span class="number">30</span>;</span><br><span class="line">        tv.tv_usec = <span class="number">0</span>;</span><br><span class="line">        <span class="comment">/*添加客户端套接字*/</span></span><br><span class="line">        <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; s_srv_ctx-&gt;cli_cnt; i++) &#123;</span><br><span class="line">            clifd = s_srv_ctx-&gt;clifds[i];</span><br><span class="line">            <span class="comment">/*去除无效的客户端句柄*/</span></span><br><span class="line">            <span class="keyword">if</span> (clifd != <span class="number">-1</span>) &#123;</span><br><span class="line">                FD_SET(clifd, readfds);</span><br><span class="line">            &#125;</span><br><span class="line">            s_srv_ctx-&gt;maxfd = (clifd &gt; s_srv_ctx-&gt;maxfd ? clifd : s_srv_ctx-&gt;maxfd);</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/*开始轮询接收处理服务端和客户端套接字*/</span></span><br><span class="line">        retval = select(s_srv_ctx-&gt;maxfd + <span class="number">1</span>, readfds, <span class="literal">NULL</span>, <span class="literal">NULL</span>, &amp;tv);</span><br><span class="line">        <span class="keyword">if</span> (retval == <span class="number">-1</span>) &#123;</span><br><span class="line">            <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">"select error:%s.\n"</span>, strerror(errno));</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (retval == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="built_in">fprintf</span>(<span class="built_in">stdout</span>, <span class="string">"select is timeout.\n"</span>);</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (FD_ISSET(srvfd, readfds)) &#123;</span><br><span class="line">            <span class="comment">/*监听客户端请求*/</span></span><br><span class="line">            accept_client_proc(srvfd);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">/*接受处理客户端消息*/</span></span><br><span class="line">            recv_client_msg(readfds);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">server_uninit</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (s_srv_ctx) &#123;</span><br><span class="line">        <span class="built_in">free</span>(s_srv_ctx);</span><br><span class="line">        s_srv_ctx = <span class="literal">NULL</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">server_init</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    s_srv_ctx = (server_context_st *)<span class="built_in">malloc</span>(<span class="keyword">sizeof</span>(server_context_st));</span><br><span class="line">    <span class="keyword">if</span> (s_srv_ctx == <span class="literal">NULL</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">memset</span>(s_srv_ctx, <span class="number">0</span>, <span class="keyword">sizeof</span>(server_context_st));</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (;i &lt; SIZE; i++) &#123;</span><br><span class="line">        s_srv_ctx-&gt;clifds[i] = <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc,<span class="keyword">char</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>  srvfd;</span><br><span class="line">    <span class="comment">/*初始化服务端context*/</span></span><br><span class="line">    <span class="keyword">if</span> (server_init() &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/*创建服务,开始监听客户端请求*/</span></span><br><span class="line">    srvfd = create_server_proc(IPADDR, PORT);</span><br><span class="line">    <span class="keyword">if</span> (srvfd &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">"socket create or bind fail.\n"</span>);</span><br><span class="line">        <span class="keyword">goto</span> err;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/*开始接收并处理客户端请求*/</span></span><br><span class="line">    handle_client_proc(srvfd);</span><br><span class="line">    server_uninit();</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">err:</span><br><span class="line">    server_uninit();</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>客户端：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;netinet/in.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/socket.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/select.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;time.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;errno.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> MAXLINE 1024</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> IPADDRESS <span class="meta-string">"127.0.0.1"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> SERV_PORT 8787</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> max(a,b) (a &gt; b) ? a : b</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle_recv_msg</span><span class="params">(<span class="keyword">int</span> sockfd, <span class="keyword">char</span> *buf)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"client recv msg is:%s\n"</span>, buf);</span><br><span class="line">    sleep(<span class="number">5</span>);</span><br><span class="line">    write(sockfd, buf, <span class="built_in">strlen</span>(buf) +<span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle_connection</span><span class="params">(<span class="keyword">int</span> sockfd)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">char</span> sendline[MAXLINE],recvline[MAXLINE];</span><br><span class="line">    <span class="keyword">int</span> maxfdp,stdineof;</span><br><span class="line">    fd_set readfds;</span><br><span class="line">    <span class="keyword">int</span> n;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">timeval</span> <span class="title">tv</span>;</span></span><br><span class="line">    <span class="keyword">int</span> retval = <span class="number">0</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span> (<span class="number">1</span>) &#123;</span><br><span class="line">        </span><br><span class="line">        FD_ZERO(&amp;readfds);</span><br><span class="line">        FD_SET(sockfd,&amp;readfds);</span><br><span class="line">        maxfdp = sockfd;</span><br><span class="line">        </span><br><span class="line">        tv.tv_sec = <span class="number">5</span>;</span><br><span class="line">        tv.tv_usec = <span class="number">0</span>;</span><br><span class="line">        </span><br><span class="line">        retval = select(maxfdp+<span class="number">1</span>,&amp;readfds,<span class="literal">NULL</span>,<span class="literal">NULL</span>,&amp;tv);</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (retval == <span class="number">-1</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> ;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (retval == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">"client timeout.\n"</span>);</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (FD_ISSET(sockfd, &amp;readfds)) &#123;</span><br><span class="line">            n = read(sockfd,recvline,MAXLINE);</span><br><span class="line">            <span class="keyword">if</span> (n &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>,<span class="string">"client: server is closed.\n"</span>);</span><br><span class="line">                close(sockfd);</span><br><span class="line">                FD_CLR(sockfd,&amp;readfds);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            </span><br><span class="line">            handle_recv_msg(sockfd, recvline);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc,<span class="keyword">char</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> sockfd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">sockaddr_in</span> <span class="title">servaddr</span>;</span></span><br><span class="line">    </span><br><span class="line">    sockfd = socket(AF_INET,SOCK_STREAM,<span class="number">0</span>);</span><br><span class="line">    </span><br><span class="line">    bzero(&amp;servaddr,<span class="keyword">sizeof</span>(servaddr));</span><br><span class="line">    servaddr.sin_family = AF_INET;</span><br><span class="line">    servaddr.sin_port = htons(SERV_PORT);</span><br><span class="line">    inet_pton(AF_INET,IPADDRESS,&amp;servaddr.sin_addr);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">int</span> retval = <span class="number">0</span>;</span><br><span class="line">    retval = connect(sockfd,(struct sockaddr*)&amp;servaddr,<span class="keyword">sizeof</span>(servaddr));</span><br><span class="line">    <span class="keyword">if</span> (retval &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">"connect fail,error:%s\n"</span>, strerror(errno));</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"client send to server .\n"</span>);</span><br><span class="line">    write(sockfd, <span class="string">"hello server"</span>, <span class="number">32</span>);</span><br><span class="line">    </span><br><span class="line">    handle_connection(sockfd);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="IO多路复用之poll总结"><a href="#IO多路复用之poll总结" class="headerlink" title="IO多路复用之poll总结"></a>IO多路复用之poll总结</h4><h5 id="概念-1"><a href="#概念-1" class="headerlink" title="概念"></a>概念</h5><p>poll的机制与select类似，与select在本质上没有多大差别，管理多个描述符也是进行轮询，根据描述符的状态进行处理，但是poll没有最大文件描述符数量的限制.</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># <span class="meta-keyword">include</span> <span class="meta-string">&lt;poll.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">poll</span> <span class="params">( struct pollfd * fds, <span class="keyword">unsigned</span> <span class="keyword">int</span> nfds, <span class="keyword">int</span> timeout)</span></span>;</span><br></pre></td></tr></table></figure>

<p><strong>pollfd结构体定义如下</strong>：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">pollfd</span> &#123;</span></span><br><span class="line">    <span class="keyword">int</span> fd;        		  <span class="comment">/* 文件描述符 */</span></span><br><span class="line">    <span class="keyword">short</span> events;         <span class="comment">/* 等待的事件 */</span></span><br><span class="line">    <span class="keyword">short</span> revents;        <span class="comment">/* 实际发生了的事件 */</span></span><br><span class="line">&#125; ;</span><br></pre></td></tr></table></figure>

<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 等待的事件 */</span></span><br><span class="line">POLLIN 　　　　　　　　有数据可读。</span><br><span class="line">POLLRDNORM 　　　　  有普通数据可读。</span><br><span class="line">POLLRDBAND　　　　　 有优先数据可读。</span><br><span class="line">POLLPRI　　　　　　　　 有紧迫数据可读。</span><br><span class="line">POLLOUT　　　　　　      写数据不会导致阻塞。</span><br><span class="line">POLLWRNORM　　　　　  写普通数据不会导致阻塞。</span><br><span class="line">POLLWRBAND　　　　　   写优先数据不会导致阻塞。</span><br><span class="line">POLLMSGSIGPOLL 　　　　消息可用。</span><br><span class="line"><span class="comment">/* 实际发生了的事件 */</span></span><br><span class="line">POLLER　　   指定的文件描述符发生错误。</span><br><span class="line">POLLHUP　　 指定的文件描述符挂起事件。</span><br><span class="line">POLLNVAL　　指定的文件描述符非法。</span><br></pre></td></tr></table></figure>

<ul>
<li>POLLIN | POLLPRI等价于select()的读事件，POLLOUT |POLLWRBAND等价于select()的写事件。</li>
<li>POLLIN等价于POLLRDNORM |POLLRDBAND，而POLLOUT则等价于POLLWRNORM。</li>
</ul>
<blockquote>
<p>例如，要同时监视一个文件描述符是否可读和可写，我们可以设置 events为POLLIN |POLLOUT。在poll返回时，我们可以检查revents中的标志，对应于文件描述符请求的events结构体。如果POLLIN事件被设置，则文件描述符可以被读取而不阻塞。如果POLLOUT被设置，则文件描述符可以写入而不导致阻塞。这些标志并不是互斥的：它们可能被同时设置，表示这个文件描述符的读取和写入操作都会正常返回而不阻塞。</p>
</blockquote>
<p><strong>timeout参数指定等待的毫秒数，无论I/O是否准备好，poll都会返回。</strong></p>
<ul>
<li><p>timeout指定为负数值表示无限超时，使poll()一直挂起直到一个指定事件发生；</p>
</li>
<li><p>timeout为0指示poll调用立即返回并列出准备好I/O的文件描述符，但并不等待其它的事件。这种情况下，poll()就像它的名字那样，一旦选举出来，立即返回。</p>
</li>
</ul>
<p><strong>返回值和错误代码</strong></p>
<ul>
<li><p>成功时，poll()返回结构体中revents域不为0的文件描述符个数；</p>
</li>
<li><p>如果在超时前没有任何事件发生，poll()返回0；</p>
</li>
<li><p>失败时，poll()返回-1，并设置err下列值之一：</p>
</li>
</ul>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">EBADF　　       <span class="comment">//一个或多个结构体中指定的文件描述符无效。</span></span><br><span class="line">EFAULTfds　　 <span class="comment">//指针指向的地址超出进程的地址空间。</span></span><br><span class="line">EINTR　　　　  <span class="comment">//请求的事件之前产生一个信号，调用可以重新发起。</span></span><br><span class="line">EINVALnfds　　<span class="comment">//参数超出PLIMIT_NOFILE值。</span></span><br><span class="line">ENOMEM　　     <span class="comment">//可用内存不足，无法完成请求。</span></span><br></pre></td></tr></table></figure>

<h5 id="测试代码-1"><a href="#测试代码-1" class="headerlink" title="测试代码"></a>测试代码</h5><p>客户端向服务器发送信息，服务器接收并原样发送给客户端，客户端显示出接收到的信息。</p>
<p>服务器端程序:</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;errno.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;netinet/in.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/socket.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;poll.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> IPADDRESS   <span class="meta-string">"127.0.0.1"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> PORT        8787</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> MAXLINE     1024</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> LISTENQ     5</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> OPEN_MAX    1000</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> INFTIM      -1</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//函数声明</span></span><br><span class="line"><span class="comment">//创建套接字并进行绑定</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">socket_bind</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span>* ip,<span class="keyword">int</span> port)</span></span>;</span><br><span class="line"><span class="comment">//IO多路复用poll</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_poll</span><span class="params">(<span class="keyword">int</span> listenfd)</span></span>;</span><br><span class="line"><span class="comment">//处理多个连接</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle_connection</span><span class="params">(struct pollfd *connfds,<span class="keyword">int</span> num)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc,<span class="keyword">char</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>  listenfd,connfd,sockfd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">sockaddr_in</span> <span class="title">cliaddr</span>;</span></span><br><span class="line">    <span class="keyword">socklen_t</span> cliaddrlen;</span><br><span class="line">    listenfd = socket_bind(IPADDRESS,PORT);</span><br><span class="line">    listen(listenfd,LISTENQ);</span><br><span class="line">    do_poll(listenfd);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">socket_bind</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span>* ip,<span class="keyword">int</span> port)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>  listenfd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">sockaddr_in</span> <span class="title">servaddr</span>;</span></span><br><span class="line">    listenfd = socket(AF_INET,SOCK_STREAM,<span class="number">0</span>);</span><br><span class="line">    <span class="keyword">if</span> (listenfd == <span class="number">-1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        perror(<span class="string">"socket error:"</span>);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    bzero(&amp;servaddr,<span class="keyword">sizeof</span>(servaddr));</span><br><span class="line">    servaddr.sin_family = AF_INET;</span><br><span class="line">    inet_pton(AF_INET,ip,&amp;servaddr.sin_addr);</span><br><span class="line">    servaddr.sin_port = htons(port);</span><br><span class="line">    <span class="keyword">if</span> (bind(listenfd,(struct sockaddr*)&amp;servaddr,<span class="keyword">sizeof</span>(servaddr)) == <span class="number">-1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        perror(<span class="string">"bind error: "</span>);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> listenfd;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_poll</span><span class="params">(<span class="keyword">int</span> listenfd)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>  connfd,sockfd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">sockaddr_in</span> <span class="title">cliaddr</span>;</span></span><br><span class="line">    <span class="keyword">socklen_t</span> cliaddrlen;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">pollfd</span> <span class="title">clientfds</span>[<span class="title">OPEN_MAX</span>];</span></span><br><span class="line">    <span class="keyword">int</span> maxi;</span><br><span class="line">    <span class="keyword">int</span> i;</span><br><span class="line">    <span class="keyword">int</span> nready;</span><br><span class="line">    <span class="comment">//添加监听描述符</span></span><br><span class="line">    clientfds[<span class="number">0</span>].fd = listenfd;</span><br><span class="line">    clientfds[<span class="number">0</span>].events = POLLIN;</span><br><span class="line">    <span class="comment">//初始化客户连接描述符</span></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">1</span>;i &lt; OPEN_MAX;i++)</span><br><span class="line">        clientfds[i].fd = <span class="number">-1</span>;</span><br><span class="line">    maxi = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">//循环处理</span></span><br><span class="line">    <span class="keyword">for</span> ( ; ; )</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//获取可用描述符的个数</span></span><br><span class="line">        nready = poll(clientfds,maxi+<span class="number">1</span>,INFTIM);</span><br><span class="line">        <span class="keyword">if</span> (nready == <span class="number">-1</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            perror(<span class="string">"poll error:"</span>);</span><br><span class="line">            <span class="built_in">exit</span>(<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//测试监听描述符是否准备好</span></span><br><span class="line">        <span class="keyword">if</span> (clientfds[<span class="number">0</span>].revents &amp; POLLIN)</span><br><span class="line">        &#123;</span><br><span class="line">            cliaddrlen = <span class="keyword">sizeof</span>(cliaddr);</span><br><span class="line">            <span class="comment">//接受新的连接</span></span><br><span class="line">            <span class="keyword">if</span> ((connfd = accept(listenfd,(struct sockaddr*)&amp;cliaddr,&amp;cliaddrlen)) == <span class="number">-1</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">if</span> (errno == EINTR)</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                <span class="keyword">else</span></span><br><span class="line">                &#123;</span><br><span class="line">                    perror(<span class="string">"accept error:"</span>);</span><br><span class="line">                    <span class="built_in">exit</span>(<span class="number">1</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">fprintf</span>(<span class="built_in">stdout</span>,<span class="string">"accept a new client: %s:%d\n"</span>, inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port);</span><br><span class="line">            <span class="comment">//将新的连接描述符添加到数组中</span></span><br><span class="line">            <span class="keyword">for</span> (i = <span class="number">1</span>;i &lt; OPEN_MAX;i++)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">if</span> (clientfds[i].fd &lt; <span class="number">0</span>)</span><br><span class="line">                &#123;</span><br><span class="line">                    clientfds[i].fd = connfd;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (i == OPEN_MAX)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>,<span class="string">"too many clients.\n"</span>);</span><br><span class="line">                <span class="built_in">exit</span>(<span class="number">1</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//将新的描述符添加到读描述符集合中</span></span><br><span class="line">            clientfds[i].events = POLLIN;</span><br><span class="line">            <span class="comment">//记录客户连接套接字的个数</span></span><br><span class="line">            maxi = (i &gt; maxi ? i : maxi);</span><br><span class="line">            <span class="keyword">if</span> (--nready &lt;= <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//处理客户连接</span></span><br><span class="line">        handle_connection(clientfds,maxi);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle_connection</span><span class="params">(struct pollfd *connfds,<span class="keyword">int</span> num)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i,n;</span><br><span class="line">    <span class="keyword">char</span> buf[MAXLINE];</span><br><span class="line">    <span class="built_in">memset</span>(buf,<span class="number">0</span>,MAXLINE);</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">1</span>;i &lt;= num;i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span> (connfds[i].fd &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        <span class="comment">//测试客户描述符是否准备好</span></span><br><span class="line">        <span class="keyword">if</span> (connfds[i].revents &amp; POLLIN)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="comment">//接收客户端发送的信息</span></span><br><span class="line">            n = read(connfds[i].fd,buf,MAXLINE);</span><br><span class="line">            <span class="keyword">if</span> (n == <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                close(connfds[i].fd);</span><br><span class="line">                connfds[i].fd = <span class="number">-1</span>;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// printf("read msg is: ");</span></span><br><span class="line">            write(STDOUT_FILENO,buf,n);</span><br><span class="line">            <span class="comment">//向客户端发送buf</span></span><br><span class="line">            write(connfds[i].fd,buf,n);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>客户端代码:</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;netinet/in.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/socket.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;poll.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;time.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> MAXLINE     1024</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> IPADDRESS   <span class="meta-string">"127.0.0.1"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> SERV_PORT   8787</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> max(a,b) (a &gt; b) ? a : b</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle_connection</span><span class="params">(<span class="keyword">int</span> sockfd)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc,<span class="keyword">char</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>                 sockfd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">sockaddr_in</span>  <span class="title">servaddr</span>;</span></span><br><span class="line">    sockfd = socket(AF_INET,SOCK_STREAM,<span class="number">0</span>);</span><br><span class="line">    bzero(&amp;servaddr,<span class="keyword">sizeof</span>(servaddr));</span><br><span class="line">    servaddr.sin_family = AF_INET;</span><br><span class="line">    servaddr.sin_port = htons(SERV_PORT);</span><br><span class="line">    inet_pton(AF_INET,IPADDRESS,&amp;servaddr.sin_addr);</span><br><span class="line">    connect(sockfd,(struct sockaddr*)&amp;servaddr,<span class="keyword">sizeof</span>(servaddr));</span><br><span class="line">    <span class="comment">//处理连接描述符</span></span><br><span class="line">    handle_connection(sockfd);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle_connection</span><span class="params">(<span class="keyword">int</span> sockfd)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">char</span>    sendline[MAXLINE],recvline[MAXLINE];</span><br><span class="line">    <span class="keyword">int</span>     maxfdp,stdineof;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">pollfd</span> <span class="title">pfds</span>[2];</span></span><br><span class="line">    <span class="keyword">int</span> n;</span><br><span class="line">    <span class="comment">//添加连接描述符</span></span><br><span class="line">    pfds[<span class="number">0</span>].fd = sockfd;</span><br><span class="line">    pfds[<span class="number">0</span>].events = POLLIN;</span><br><span class="line">    <span class="comment">//添加标准输入描述符</span></span><br><span class="line">    pfds[<span class="number">1</span>].fd = STDIN_FILENO;</span><br><span class="line">    pfds[<span class="number">1</span>].events = POLLIN;</span><br><span class="line">    <span class="keyword">for</span> (; ;)</span><br><span class="line">    &#123;</span><br><span class="line">        poll(pfds,<span class="number">2</span>,<span class="number">-1</span>);</span><br><span class="line">        <span class="keyword">if</span> (pfds[<span class="number">0</span>].revents &amp; POLLIN)</span><br><span class="line">        &#123;</span><br><span class="line">            n = read(sockfd,recvline,MAXLINE);</span><br><span class="line">            <span class="keyword">if</span> (n == <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>,<span class="string">"client: server is closed.\n"</span>);</span><br><span class="line">                close(sockfd);</span><br><span class="line">            &#125;</span><br><span class="line">            write(STDOUT_FILENO,recvline,n);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//测试标准输入是否准备好</span></span><br><span class="line">        <span class="keyword">if</span> (pfds[<span class="number">1</span>].revents &amp; POLLIN)</span><br><span class="line">        &#123;</span><br><span class="line">            n = read(STDIN_FILENO,sendline,MAXLINE);</span><br><span class="line">            <span class="keyword">if</span> (n  == <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                shutdown(sockfd,SHUT_WR);</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            write(sockfd,sendline,n);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="IO多路复用之epoll总结"><a href="#IO多路复用之epoll总结" class="headerlink" title="IO多路复用之epoll总结"></a>IO多路复用之epoll总结</h4><h5 id="概念-2"><a href="#概念-2" class="headerlink" title="概念"></a>概念</h5><p>​    epoll是在2.6内核中提出的，是之前的select和poll的增强版本。相对于select和poll来说，epoll更加灵活，没有描述符限制。epoll使用一个文件描述符管理多个描述符，将用户关系的文件描述符的事件存放到内核的一个事件表中，这样在用户空间和内核空间的copy只需一次。</p>
<p>epoll操作过程需要三个接口，分别如下：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/epoll.h&gt; </span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">epoll_create</span><span class="params">(<span class="keyword">int</span> size)</span></span>;</span><br></pre></td></tr></table></figure>

<p>　　创建一个epoll的句柄，size用来告诉内核这个监听的数目一共有多大。这个参数不同于select()中的第一个参数，给出最大监听的fd+1的值。需要注意的是，当创建好epoll句柄后，它就是会占用一个fd值，在linux下如果查看/proc/进程id/fd/，是能够看到这个fd的，所以在使用完epoll后，必须调用close()关闭，否则可能导致fd被耗尽。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">epoll_ctl</span><span class="params">(<span class="keyword">int</span> epfd, <span class="keyword">int</span> op, <span class="keyword">int</span> fd, struct epoll_event \*event)</span></span>;</span><br></pre></td></tr></table></figure>

<p>　　epoll的事件注册函数，它不同与select()是在监听事件时告诉内核要监听什么类型的事件epoll的事件注册函数，它不同与select()是在监听事件时告诉内核要监听什么类型的事件，而是在这里先注册要监听的事件类型。</p>
<p>第一个参数是epoll_create()的返回值，第二个参数表示动作，用三个宏来表示：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">EPOLL_CTL_ADD <span class="comment">// 注册新的fd到epfd中；</span></span><br><span class="line">EPOLL_CTL_MOD <span class="comment">// 修改已经注册的fd的监听事件；</span></span><br><span class="line">EPOLL_CTL_DEL <span class="comment">// 从epfd中删除一个fd；</span></span><br></pre></td></tr></table></figure>

<p>第三个参数是需要监听的fd，第四个参数是告诉内核需要监听什么事，struct epoll_event结构如下：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">epoll_event</span> &#123;</span></span><br><span class="line">  <span class="keyword">__uint32_t</span> events;  <span class="comment">/* Epoll events */</span></span><br><span class="line">  <span class="keyword">epoll_data_t</span> data;  <span class="comment">/* User data variable */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>events可以是以下几个宏的集合：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">EPOLLIN <span class="comment">// 表示对应的文件描述符可以读（包括对端SOCKET正常关闭）；</span></span><br><span class="line">EPOLLOUT <span class="comment">//表示对应的文件描述符可以写；</span></span><br><span class="line">EPOLLPRI <span class="comment">// 表示对应的文件描述符有紧急的数据可读（这里应该表示有带外数据到来）；</span></span><br><span class="line">EPOLLERR <span class="comment">// 表示对应的文件描述符发生错误；</span></span><br><span class="line">EPOLLHUP <span class="comment">// 表示对应的文件描述符被挂断；</span></span><br><span class="line">EPOLLET  <span class="comment">// 将EPOLL设为边缘触发(Edge Triggered)模式，这是相对于水平触发(Level Triggered)来说的。</span></span><br><span class="line">EPOLLONESHOT <span class="comment">// 只监听一次事件，当监听完这次事件之后，如果还需要继续监听这个socket的话，需要再次把这个socket加入到EPOLL队列里</span></span><br></pre></td></tr></table></figure>

<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">epoll_wait</span><span class="params">(<span class="keyword">int</span> epfd, struct epoll_event \* events, <span class="keyword">int</span> maxevents, <span class="keyword">int</span> timeout)</span></span>;</span><br></pre></td></tr></table></figure>

<p>　　等待事件的产生，类似于select()调用。参数events用来从内核得到事件的集合，maxevents告之内核这个events有多大，这个maxevents的值不能大于创建epoll_create()时的size，参数timeout是超时时间（毫秒，0会立即返回，-1将不确定，也有说法说是永久阻塞）。该函数返回需要处理的事件数目，如返回0表示已超时。</p>
<h5 id="工作模式"><a href="#工作模式" class="headerlink" title="工作模式"></a>工作模式</h5><p>　epoll对文件描述符的操作有两种模式：LT（level trigger）和ET（edge trigger）。LT模式是默认模式，LT模式与ET模式的区别如下：</p>
<p>　　LT模式：<strong>当epoll_wait检测到描述符事件发生并将此事件通知应用程序，应用程序可以不立即处理该事件。下次调用epoll_wait时，会再次响应应用程序并通知此事件。</strong></p>
<p>　　ET模式：<strong>当epoll_wait检测到描述符事件发生并将此事件通知应用程序，应用程序必须立即处理该事件。如果不处理，下次调用epoll_wait时，不会再次响应应用程序并通知此事件。</strong></p>
<p>　　ET模式在很大程度上减少了epoll事件被重复触发的次数，因此效率要比LT模式高。epoll工作在ET模式的时候，必须使用非阻塞套接口，以避免由于一个文件句柄的阻塞读/阻塞写操作把处理多个文件描述符的任务饿死。</p>
<h5 id="测试程序"><a href="#测试程序" class="headerlink" title="测试程序"></a>测试程序</h5><p>服务端：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;errno.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;netinet/in.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/socket.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;arpa/inet.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/epoll.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> IPADDRESS   <span class="meta-string">"127.0.0.1"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> PORT        8787</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> MAXSIZE     1024</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> LISTENQ     5</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> FDSIZE      1000</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> EPOLLEVENTS 100</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//函数声明</span></span><br><span class="line"><span class="comment">//创建套接字并进行绑定</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">socket_bind</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span>* ip,<span class="keyword">int</span> port)</span></span>;</span><br><span class="line"><span class="comment">//IO多路复用epoll</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_epoll</span><span class="params">(<span class="keyword">int</span> listenfd)</span></span>;</span><br><span class="line"><span class="comment">//事件处理函数</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">void</span></span><br><span class="line">handle_events(<span class="keyword">int</span> epollfd,struct epoll_event *events,<span class="keyword">int</span> num,<span class="keyword">int</span> listenfd,<span class="keyword">char</span> *buf);</span><br><span class="line"><span class="comment">//处理接收到的连接</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle_accpet</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> listenfd)</span></span>;</span><br><span class="line"><span class="comment">//读处理</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_read</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">char</span> *buf)</span></span>;</span><br><span class="line"><span class="comment">//写处理</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_write</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">char</span> *buf)</span></span>;</span><br><span class="line"><span class="comment">//添加事件</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">add_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span>;</span><br><span class="line"><span class="comment">//修改事件</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">modify_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span>;</span><br><span class="line"><span class="comment">//删除事件</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">delete_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc,<span class="keyword">char</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>  listenfd;</span><br><span class="line">    listenfd = socket_bind(IPADDRESS,PORT);</span><br><span class="line">    listen(listenfd,LISTENQ);</span><br><span class="line">    do_epoll(listenfd);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">socket_bind</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span>* ip,<span class="keyword">int</span> port)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>  listenfd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">sockaddr_in</span> <span class="title">servaddr</span>;</span></span><br><span class="line">    listenfd = socket(AF_INET,SOCK_STREAM,<span class="number">0</span>);</span><br><span class="line">    <span class="keyword">if</span> (listenfd == <span class="number">-1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        perror(<span class="string">"socket error:"</span>);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    bzero(&amp;servaddr,<span class="keyword">sizeof</span>(servaddr));</span><br><span class="line">    servaddr.sin_family = AF_INET;</span><br><span class="line">    inet_pton(AF_INET,ip,&amp;servaddr.sin_addr);</span><br><span class="line">    servaddr.sin_port = htons(port);</span><br><span class="line">    <span class="keyword">if</span> (bind(listenfd,(struct sockaddr*)&amp;servaddr,<span class="keyword">sizeof</span>(servaddr)) == <span class="number">-1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        perror(<span class="string">"bind error: "</span>);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> listenfd;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_epoll</span><span class="params">(<span class="keyword">int</span> listenfd)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> epollfd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">epoll_event</span> <span class="title">events</span>[<span class="title">EPOLLEVENTS</span>];</span></span><br><span class="line">    <span class="keyword">int</span> ret;</span><br><span class="line">    <span class="keyword">char</span> buf[MAXSIZE];</span><br><span class="line">    <span class="built_in">memset</span>(buf,<span class="number">0</span>,MAXSIZE);</span><br><span class="line">    <span class="comment">//创建一个描述符</span></span><br><span class="line">    epollfd = epoll_create(FDSIZE);</span><br><span class="line">    <span class="comment">//添加监听描述符事件</span></span><br><span class="line">    add_event(epollfd,listenfd,EPOLLIN);</span><br><span class="line">    <span class="keyword">for</span> ( ; ; )</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//获取已经准备好的描述符事件</span></span><br><span class="line">        ret = epoll_wait(epollfd,events,EPOLLEVENTS,<span class="number">-1</span>);</span><br><span class="line">        handle_events(epollfd,events,ret,listenfd,buf);</span><br><span class="line">    &#125;</span><br><span class="line">    close(epollfd);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">void</span></span><br><span class="line">handle_events(<span class="keyword">int</span> epollfd,struct epoll_event *events,<span class="keyword">int</span> num,<span class="keyword">int</span> listenfd,<span class="keyword">char</span> *buf)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">int</span> i;</span><br><span class="line">    <span class="keyword">int</span> fd;</span><br><span class="line">    <span class="comment">//进行选好遍历</span></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>;i &lt; num;i++)</span><br><span class="line">    &#123;</span><br><span class="line">        fd = events[i].data.fd;</span><br><span class="line">        <span class="comment">//根据描述符的类型和事件类型进行处理</span></span><br><span class="line">        <span class="keyword">if</span> ((fd == listenfd) &amp;&amp;(events[i].events &amp; EPOLLIN))</span><br><span class="line">            handle_accpet(epollfd,listenfd);</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (events[i].events &amp; EPOLLIN)</span><br><span class="line">            do_read(epollfd,fd,buf);</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (events[i].events &amp; EPOLLOUT)</span><br><span class="line">            do_write(epollfd,fd,buf);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle_accpet</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> listenfd)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> clifd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">sockaddr_in</span> <span class="title">cliaddr</span>;</span></span><br><span class="line">    <span class="keyword">socklen_t</span>  cliaddrlen;</span><br><span class="line">    clifd = accept(listenfd,(struct sockaddr*)&amp;cliaddr,&amp;cliaddrlen);</span><br><span class="line">    <span class="keyword">if</span> (clifd == <span class="number">-1</span>)</span><br><span class="line">        perror(<span class="string">"accpet error:"</span>);</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"accept a new client: %s:%d\n"</span>,inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port);</span><br><span class="line">        <span class="comment">//添加一个客户描述符和事件</span></span><br><span class="line">        add_event(epollfd,clifd,EPOLLIN);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_read</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">char</span> *buf)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> nread;</span><br><span class="line">    nread = read(fd,buf,MAXSIZE);</span><br><span class="line">    <span class="keyword">if</span> (nread == <span class="number">-1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        perror(<span class="string">"read error:"</span>);</span><br><span class="line">        close(fd);</span><br><span class="line">        delete_event(epollfd,fd,EPOLLIN);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (nread == <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>,<span class="string">"client close.\n"</span>);</span><br><span class="line">        close(fd);</span><br><span class="line">        delete_event(epollfd,fd,EPOLLIN);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"read message is : %s"</span>,buf);</span><br><span class="line">        <span class="comment">//修改描述符对应的事件，由读改为写</span></span><br><span class="line">        modify_event(epollfd,fd,EPOLLOUT);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_write</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">char</span> *buf)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> nwrite;</span><br><span class="line">    nwrite = write(fd,buf,<span class="built_in">strlen</span>(buf));</span><br><span class="line">    <span class="keyword">if</span> (nwrite == <span class="number">-1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        perror(<span class="string">"write error:"</span>);</span><br><span class="line">        close(fd);</span><br><span class="line">        delete_event(epollfd,fd,EPOLLOUT);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        modify_event(epollfd,fd,EPOLLIN);</span><br><span class="line">    <span class="built_in">memset</span>(buf,<span class="number">0</span>,MAXSIZE);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">add_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">epoll_event</span> <span class="title">ev</span>;</span></span><br><span class="line">    ev.events = state;</span><br><span class="line">    ev.data.fd = fd;</span><br><span class="line">    epoll_ctl(epollfd,EPOLL_CTL_ADD,fd,&amp;ev);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">delete_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">epoll_event</span> <span class="title">ev</span>;</span></span><br><span class="line">    ev.events = state;</span><br><span class="line">    ev.data.fd = fd;</span><br><span class="line">    epoll_ctl(epollfd,EPOLL_CTL_DEL,fd,&amp;ev);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">modify_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">epoll_event</span> <span class="title">ev</span>;</span></span><br><span class="line">    ev.events = state;</span><br><span class="line">    ev.data.fd = fd;</span><br><span class="line">    epoll_ctl(epollfd,EPOLL_CTL_MOD,fd,&amp;ev);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>客户端：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;netinet/in.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/socket.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/epoll.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;time.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;arpa/inet.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> MAXSIZE     1024</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> IPADDRESS   <span class="meta-string">"127.0.0.1"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> SERV_PORT   8787</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> FDSIZE        1024</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> EPOLLEVENTS 20</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle_connection</span><span class="params">(<span class="keyword">int</span> sockfd)</span></span>;</span><br><span class="line"><span class="keyword">static</span> <span class="keyword">void</span></span><br><span class="line">handle_events(<span class="keyword">int</span> epollfd,struct epoll_event *events,<span class="keyword">int</span> num,<span class="keyword">int</span> sockfd,<span class="keyword">char</span> *buf);</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_read</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> sockfd,<span class="keyword">char</span> *buf)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_read</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> sockfd,<span class="keyword">char</span> *buf)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_write</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> sockfd,<span class="keyword">char</span> *buf)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">add_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">delete_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">modify_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc,<span class="keyword">char</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span>                 sockfd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">sockaddr_in</span>  <span class="title">servaddr</span>;</span></span><br><span class="line">    sockfd = socket(AF_INET,SOCK_STREAM,<span class="number">0</span>);</span><br><span class="line">    bzero(&amp;servaddr,<span class="keyword">sizeof</span>(servaddr));</span><br><span class="line">    servaddr.sin_family = AF_INET;</span><br><span class="line">    servaddr.sin_port = htons(SERV_PORT);</span><br><span class="line">    inet_pton(AF_INET,IPADDRESS,&amp;servaddr.sin_addr);</span><br><span class="line">    connect(sockfd,(struct sockaddr*)&amp;servaddr,<span class="keyword">sizeof</span>(servaddr));</span><br><span class="line">    <span class="comment">//处理连接</span></span><br><span class="line">    handle_connection(sockfd);</span><br><span class="line">    close(sockfd);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle_connection</span><span class="params">(<span class="keyword">int</span> sockfd)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> epollfd;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">epoll_event</span> <span class="title">events</span>[<span class="title">EPOLLEVENTS</span>];</span></span><br><span class="line">    <span class="keyword">char</span> buf[MAXSIZE];</span><br><span class="line">    <span class="keyword">int</span> ret;</span><br><span class="line">    epollfd = epoll_create(FDSIZE);</span><br><span class="line">    add_event(epollfd,STDIN_FILENO,EPOLLIN);</span><br><span class="line">    <span class="keyword">for</span> ( ; ; )</span><br><span class="line">    &#123;</span><br><span class="line">        ret = epoll_wait(epollfd,events,EPOLLEVENTS,<span class="number">-1</span>);</span><br><span class="line">        handle_events(epollfd,events,ret,sockfd,buf);</span><br><span class="line">    &#125;</span><br><span class="line">    close(epollfd);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">void</span></span><br><span class="line">handle_events(<span class="keyword">int</span> epollfd,struct epoll_event *events,<span class="keyword">int</span> num,<span class="keyword">int</span> sockfd,<span class="keyword">char</span> *buf)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">int</span> fd;</span><br><span class="line">    <span class="keyword">int</span> i;</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>;i &lt; num;i++)</span><br><span class="line">    &#123;</span><br><span class="line">        fd = events[i].data.fd;</span><br><span class="line">        <span class="keyword">if</span> (events[i].events &amp; EPOLLIN)</span><br><span class="line">            do_read(epollfd,fd,sockfd,buf);</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (events[i].events &amp; EPOLLOUT)</span><br><span class="line">            do_write(epollfd,fd,sockfd,buf);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_read</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> sockfd,<span class="keyword">char</span> *buf)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> nread;</span><br><span class="line">    nread = read(fd,buf,MAXSIZE);</span><br><span class="line">    <span class="keyword">if</span> (nread == <span class="number">-1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        perror(<span class="string">"read error:"</span>);</span><br><span class="line">        close(fd);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (nread == <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>,<span class="string">"server close.\n"</span>);</span><br><span class="line">        close(fd);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span> (fd == STDIN_FILENO)</span><br><span class="line">            add_event(epollfd,sockfd,EPOLLOUT);</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line">            delete_event(epollfd,sockfd,EPOLLIN);</span><br><span class="line">            add_event(epollfd,STDOUT_FILENO,EPOLLOUT);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">do_write</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> sockfd,<span class="keyword">char</span> *buf)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> nwrite;</span><br><span class="line">    nwrite = write(fd,buf,<span class="built_in">strlen</span>(buf));</span><br><span class="line">    <span class="keyword">if</span> (nwrite == <span class="number">-1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        perror(<span class="string">"write error:"</span>);</span><br><span class="line">        close(fd);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span> (fd == STDOUT_FILENO)</span><br><span class="line">            delete_event(epollfd,fd,EPOLLOUT);</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            modify_event(epollfd,fd,EPOLLIN);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">memset</span>(buf,<span class="number">0</span>,MAXSIZE);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">add_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">epoll_event</span> <span class="title">ev</span>;</span></span><br><span class="line">    ev.events = state;</span><br><span class="line">    ev.data.fd = fd;</span><br><span class="line">    epoll_ctl(epollfd,EPOLL_CTL_ADD,fd,&amp;ev);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">delete_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">epoll_event</span> <span class="title">ev</span>;</span></span><br><span class="line">    ev.events = state;</span><br><span class="line">    ev.data.fd = fd;</span><br><span class="line">    epoll_ctl(epollfd,EPOLL_CTL_DEL,fd,&amp;ev);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">modify_event</span><span class="params">(<span class="keyword">int</span> epollfd,<span class="keyword">int</span> fd,<span class="keyword">int</span> state)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">epoll_event</span> <span class="title">ev</span>;</span></span><br><span class="line">    ev.events = state;</span><br><span class="line">    ev.data.fd = fd;</span><br><span class="line">    epoll_ctl(epollfd,EPOLL_CTL_MOD,fd,&amp;ev);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Nagle-算法"><a href="#Nagle-算法" class="headerlink" title="Nagle 算法"></a>Nagle 算法</h3><p>默认应用于所有TCP连接的优化，避免发送大量的微型TCP分组问题。可以通过选项字节TCP_NODELAY 告诉服务器不带延迟，即时发送。</p>
<h3 id="消息划分"><a href="#消息划分" class="headerlink" title="消息划分"></a>消息划分</h3><p>EOF只有在关闭的时候发送，所以为每条消息都关闭连接，开销大，所以需要消息划分。</p>
<h4 id="使用新行-（HTTP协议）"><a href="#使用新行-（HTTP协议）" class="headerlink" title="使用新行 （HTTP协议）"></a>使用新行 （HTTP协议）</h4><p>如果是同一系统，可以使用该方法但是不同系统，会出现不兼容。</p>
<h4 id="使用内容长度"><a href="#使用内容长度" class="headerlink" title="使用内容长度"></a>使用内容长度</h4><h3 id="SSL套接字"><a href="#SSL套接字" class="headerlink" title="SSL套接字"></a>SSL套接字</h3><p>一个套接字可以升级到SSL，但是一个套接字不能同时运行两个服务，如果需要两个服务，需要开两套接口。</p>
<h3 id="紧急数据"><a href="#紧急数据" class="headerlink" title="紧急数据"></a>紧急数据</h3><p>支持将数据推送到对列前端。</p>
<p>send不带参数，同write一样，但是第二个参数MSG_OOB代表外带数据。</p>
<p>发送紧急数据，需要发送方和接受放都配合，接收方，失意难过recv，如果不存在紧急数据，调用recv第二个参数是OOB会失败。</p>
<h4 id="局限"><a href="#局限" class="headerlink" title="局限"></a>局限</h4><p>每次只能发送一个字节</p>
<h3 id="实践框架"><a href="#实践框架" class="headerlink" title="实践框架"></a>实践框架</h3><h4 id="串行化"><a href="#串行化" class="headerlink" title="串行化"></a>串行化</h4><p><strong>优点</strong></p>
<blockquote>
<p>简单，没有锁，没有共享状态</p>
</blockquote>
<p><strong>缺点</strong></p>
<blockquote>
<p>不能并发，阻塞等待</p>
</blockquote>
<h4 id="单连接进程"><a href="#单连接进程" class="headerlink" title="单连接进程"></a>单连接进程</h4><p><strong>实现原理</strong></p>
<p>fork一个子进程，获得客户端连接的副本。</p>
<p><strong>流程</strong></p>
<ol>
<li><p>连接抵达服务器</p>
</li>
<li><p>服务器接受连接</p>
</li>
<li><p>fork一个子进程</p>
</li>
<li><p>服务器返回步骤1，由子进程并行处理连接</p>
</li>
</ol>
<p><strong>优点</strong></p>
<blockquote>
<p>简单，并行，不用留心边界，没有锁。</p>
</blockquote>
<p><strong>缺点</strong></p>
<blockquote>
<p>对子进程个数没有限制</p>
</blockquote>
<h4 id="单连接线程"><a href="#单连接线程" class="headerlink" title="单连接线程"></a>单连接线程</h4><p><strong>实现原理</strong></p>
<p>accept返回的客户端套接字，传给每个线程，每个线程有自己的实例</p>
<p><strong>优点</strong></p>
<blockquote>
<p>由于每个客户端，单独一个线程处理，所以不用担心同步锁问题</p>
</blockquote>
<p><strong>缺点</strong></p>
<blockquote>
<p>线程数量没有限制</p>
</blockquote>
<h3 id="Preforking"><a href="#Preforking" class="headerlink" title="Preforking"></a>Preforking</h3><p>连接到达之前先fork进程</p>
<p><strong>处理流程</strong></p>
<ol>
<li>主服务进程创建监听套接字</li>
<li>fork一大批子进程</li>
<li>每个子进程在共享套接字上接受连接accept，然后单独处理</li>
<li>主服务器进程随时关注子进程</li>
</ol>
<p><strong>优点</strong></p>
<p>无需担心负载均衡或者子进程连接同步，内核替我们完成改功能。</p>
<p>并且内核确保，只有一个套接字副本可以接受某个特点的连接。并且限制了进程的数量。</p>
<p><strong>缺点</strong></p>
<p>fork进程较多，消耗内存较多。</p>
<h3 id="线程池"><a href="#线程池" class="headerlink" title="线程池"></a>线程池</h3><p>类似于preforking</p>
<h3 id="事件驱动"><a href="#事件驱动" class="headerlink" title="事件驱动"></a>事件驱动</h3><p><strong>处理流程</strong></p>
<ol>
<li><p>服务器监听套接字，等待套接字接入连接。</p>
</li>
<li><p>将接入的新连接加入到套接字列表进行监视。</p>
</li>
<li><p>服务器监视活动的连接以及监听套接字。</p>
</li>
<li><p>当某个活动连接可读时，服务器从该连接读取一块数据并分派相关回调函数。</p>
</li>
<li><p>当某个活动连接仍然可读时，服务器读取另外一块数据，再次分派给回调函数。</p>
</li>
<li><p>服务器收到另一个新连接时，将其加入到套接字列表进行监听。</p>
</li>
<li><p>服务器注意到第一个连接已经可写了，将响应信息写入该连接。</p>
</li>
</ol>
<p>所以这一切，都在单线程中。</p>
<p><strong>优点</strong></p>
<p>没有线程限制，所以并能力非常高</p>
<p><strong>缺点</strong></p>
<p>所有操作不能阻塞，一个缓慢的客户端，会影响该模式。</p>
<h3 id="混合模式"><a href="#混合模式" class="headerlink" title="混合模式"></a>混合模式</h3><p><strong>nginx</strong></p>
<p>preforing+事件驱动</p>

    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/socket编程/" rel="tag"># socket编程</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2019/06/19/c++11并发指南/" rel="next" title="c++11并发指南">
                  <i class="fa fa-chevron-left"></i> c++11并发指南
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2019/06/25/C++性能优化指南/" rel="prev" title="C++性能优化指南">
                  C++性能优化指南 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">

          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">XuQi</p>
  <div class="site-description motion-element" itemprop="description"></div>
</div>
  <nav class="site-state motion-element">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">44</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
        
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">30</span>
        <span class="site-state-item-name">标签</span>
        
      </div>
    
  </nav>



        </div>
      </div>
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Server的生命周期"><span class="nav-number">1.</span> <span class="nav-text">Server的生命周期</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-创建"><span class="nav-number">1.1.</span> <span class="nav-text">1. 创建</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-绑定"><span class="nav-number">1.2.</span> <span class="nav-text">2. 绑定</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-监听"><span class="nav-number">1.3.</span> <span class="nav-text">3. 监听</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-接收"><span class="nav-number">1.4.</span> <span class="nav-text">4. 接收</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-结束"><span class="nav-number">1.5.</span> <span class="nav-text">5. 结束</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Client的生命周期"><span class="nav-number">2.</span> <span class="nav-text">Client的生命周期</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-创建-1"><span class="nav-number">2.1.</span> <span class="nav-text">1. 创建</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-绑定-一般不会使用"><span class="nav-number">2.2.</span> <span class="nav-text">2. 绑定 (一般不会使用)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-连接"><span class="nav-number">2.3.</span> <span class="nav-text">3. 连接</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-结束"><span class="nav-number">2.4.</span> <span class="nav-text">4. 结束</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#套接字读操作"><span class="nav-number">3.</span> <span class="nav-text">套接字读操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#读取长度"><span class="nav-number">3.1.</span> <span class="nav-text">读取长度</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#EOF事件"><span class="nav-number">3.2.</span> <span class="nav-text">EOF事件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#部分读取"><span class="nav-number">3.3.</span> <span class="nav-text">部分读取</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#套接字写操作"><span class="nav-number">4.</span> <span class="nav-text">套接字写操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#套接字选项字节"><span class="nav-number">5.</span> <span class="nav-text">套接字选项字节</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#非阻塞式IO"><span class="nav-number">6.</span> <span class="nav-text">非阻塞式IO</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#连接复用"><span class="nav-number">7.</span> <span class="nav-text">连接复用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#IO多路复用之select总结"><span class="nav-number">7.1.</span> <span class="nav-text">IO多路复用之select总结</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#概念"><span class="nav-number">7.1.1.</span> <span class="nav-text">概念</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#基本原理"><span class="nav-number">7.1.2.</span> <span class="nav-text">基本原理</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#测试代码"><span class="nav-number">7.1.3.</span> <span class="nav-text">测试代码</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#IO多路复用之poll总结"><span class="nav-number">7.2.</span> <span class="nav-text">IO多路复用之poll总结</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#概念-1"><span class="nav-number">7.2.1.</span> <span class="nav-text">概念</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#测试代码-1"><span class="nav-number">7.2.2.</span> <span class="nav-text">测试代码</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#IO多路复用之epoll总结"><span class="nav-number">7.3.</span> <span class="nav-text">IO多路复用之epoll总结</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#概念-2"><span class="nav-number">7.3.1.</span> <span class="nav-text">概念</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#工作模式"><span class="nav-number">7.3.2.</span> <span class="nav-text">工作模式</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#测试程序"><span class="nav-number">7.3.3.</span> <span class="nav-text">测试程序</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Nagle-算法"><span class="nav-number">8.</span> <span class="nav-text">Nagle 算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#消息划分"><span class="nav-number">9.</span> <span class="nav-text">消息划分</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#使用新行-（HTTP协议）"><span class="nav-number">9.1.</span> <span class="nav-text">使用新行 （HTTP协议）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用内容长度"><span class="nav-number">9.2.</span> <span class="nav-text">使用内容长度</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SSL套接字"><span class="nav-number">10.</span> <span class="nav-text">SSL套接字</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#紧急数据"><span class="nav-number">11.</span> <span class="nav-text">紧急数据</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#局限"><span class="nav-number">11.1.</span> <span class="nav-text">局限</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实践框架"><span class="nav-number">12.</span> <span class="nav-text">实践框架</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#串行化"><span class="nav-number">12.1.</span> <span class="nav-text">串行化</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#单连接进程"><span class="nav-number">12.2.</span> <span class="nav-text">单连接进程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#单连接线程"><span class="nav-number">12.3.</span> <span class="nav-text">单连接线程</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Preforking"><span class="nav-number">13.</span> <span class="nav-text">Preforking</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程池"><span class="nav-number">14.</span> <span class="nav-text">线程池</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#事件驱动"><span class="nav-number">15.</span> <span class="nav-text">事件驱动</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#混合模式"><span class="nav-number">16.</span> <span class="nav-text">混合模式</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">XuQi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> v7.3.0</div>

        








        
      </div>
    </footer>
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
      </div>

    

  </div>

  
  <script src="/lib/jquery/index.js?v=3.4.1"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

<script src="/js/utils.js?v=7.3.0"></script>
  <script src="/js/motion.js?v=7.3.0"></script>


  <script src="/js/schemes/muse.js?v=7.3.0"></script>


<script src="/js/next-boot.js?v=7.3.0"></script>




  




























  

  

  


  
  <script src="/js/scrollspy.js?v=7.3.0"></script>
<script src="/js/post-details.js?v=7.3.0"></script>


</body>
</html>
